package org.budo.netty.servlet.server.filter.chain;

import java.io.IOException;
import java.util.List;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.Servlet;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

/**
 * @author lmw
 */
public class BudoFilterChain implements FilterChain {
    private List<Filter> filters;

    private Servlet servlet;

    private Integer index;

    public BudoFilterChain(List<Filter> filters, Servlet servlet) {
        if (null == servlet) {
            throw new IllegalArgumentException("#25 servlet can not be null, servlet=" + servlet);
        }

        this.filters = filters;
        this.servlet = servlet;
        this.index = 0;
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response) throws IOException, ServletException {
        if (null != this.filters && this.index < this.filters.size()) {
            this.index++;
            this.filters.get(this.index - 1).doFilter(request, response, this);
            return;
        }

        this.servlet.service(request, response);
    }
}